const axios = require('axios')
const {cityInfo} = require("../common/weather.city");
const {province, city} = require("../config/weather.config");
const {corpId, corpSecret, agentId} = require("../config/weather.config");
const moment = require("moment");

//获取企业微信token
const getToken = async () => {
    let url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpId}&corpsecret=${corpSecret}`
    let res = await axios.get(url)
    let token = res.data.access_token
    return token;
}
//获取城市天气
const getWeather = () => {
    return new Promise(resolve => {
        //城市id
        const city_id = cityInfo[province][city].AREAID

        //毫秒级时间戳
        const t = moment().valueOf();

        const url = `http://d1.weather.com.cn/dingzhi/${city_id}.html?_=${t}`

        axios.get(url, {
            headers: {
                "Referer": `http://www.weather.com.cn/weather1d/${city_id}.shtml`,
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
            }
        }).then(res => {
            let data = res.data.split(';')[0].split('=').slice(-1);
            data = JSON.parse(data)
            let weatherinfo = data.weatherinfo
            //信息包装
            let dataObj = {
                weather: weatherinfo.weather,
                temp: weatherinfo.temp,
                tempn: weatherinfo.tempn,
                wd:weatherinfo.wd,
                ws:weatherinfo.ws
            }
            resolve(dataObj);
        })

    })

}
//发送企业微信消息
const send_msg = async (token,description) => {

    let data = {
        "touser": "@all",
        "agentid": agentId,
        "msgtype": "textcard",
        "textcard": {
            "title": "明天的天气~",
            "description": description,
            "url": "URL",
            "btntxt": "更多"
        },
    }
    let url = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${token}&debug=1`
    let res = await axios.post(url, data)
    return res.data
}
//自执行函数
(async function () {
    let weatherInfo = await getWeather();
    let token = await getToken();
    let des=`${weatherInfo.weather}\n\n` +
        `${weatherInfo.temp}—${weatherInfo.tempn}\n\n`+
        `${weatherInfo.wd}\n${weatherInfo.ws}`;
    let res=await send_msg(token,des)
    if(res.errcode===0){
        console.log('天气推送成功！')
    }
})()
